<?php

namespace app\admin\controller;

use app\admin\api\Base;
use app\admin\service\RoleService;
use app\admin\validate\AdminValidate;
use lib\Auth;
use think\App;
use think\Controller;
use app\admin\service\AdminService;
use think\facade\Request;
class Admin extends Base
{

    public function __construct(AdminService $admin)
    {
        parent::__construct();
        $this->service = $admin;
    }

    public function logIn($userName='',$password='')
    {
        if(!$userName){
            return ['code'=>1,'msg'=>'请输入用户名'];
        }
        if(!$password){
            return ['code'=>2,'msg'=>'请输入密码'];
        }
        $token = Auth::guard()->login($userName,$password,true);
        if(!$token){
            return ['code'=>4,'msg'=>'登录失败，请重新检查账号密码输入是否正确.'];
        };


//        $data = model('Common/Admin')->get_name_one($userName);
//        if(!$data){
//            return ['code'=>3,'msg'=>'用户名错误'];
//        }
//        if($data['password'] != md5($password)){
//            return ['code'=>4,'msg'=>'密码错误'];
//        }
//        $clientkey = $data['name'] . "\t" . rand(100,999) . "\t";
//        $token = explode("\t", model('common/Staff')->ClientKey($clientkey));
        return ['code'=>0,'msg'=>'登录成功','data'=>['token'=>$token[0]]];
    }

    public function index()
    {

        $data = $this->service->getList();
        return $data;
    }

    public function save(AdminValidate $adminValidate)
    {
        $param = Request::param();
        if(!$adminValidate->check($param)){
            return ['code'=>1,'msg'=>$adminValidate->getError()];
        }

        $id = $this->service->store($param);

        return ['code'=>0,'msg'=>'新增成功！','id'=>$id];
    }

    public function read($id)
    {
        $info  = $this->service->getById($id);
        $info->roles;
        return ['code'=>0,'msg'=>'数据获取成功','data'=>$info];
    }

    public function update($id,$info=[])
    {

        $param = Request::param();

        $id = $param['id'];
        $password = $param['password'];

        if(!$this->service->isExist($id,$password)){
            return ['code'=>1,'msg'=>'输入原密码有误'];
        }

        $this->service->update($param);
        return ['code'=>0,'msg'=>'修改成功！'];
    }

    public function delete()
    {

        $id = Request::param('id');

        $this->service->destroy($id);

        return ['code'=>0,'msg'=>'删除成功'];

    }

    /**
     * 提交用户权限操作
     *
     * @return \think\Response\Redirect
     */
    public function role_store()
    {
        $data = Request::param();

        $id = $data['id'];

        $role = $data['role'];

        $this->service->role_store($id,$role);
        return ['code'=>0,'msg'=>'修改成功'];
    }
}
